package org.dawn.deveco.plugin.resourceeditor.component;

import org.dawn.deveco.plugin.resourceeditor.utils.CommonUtil;
import org.dawn.deveco.plugin.resourceeditor.utils.SwingUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * 可以伸缩的面板
 *
 * @author alan (based on others)
 * @version 0.0.1
 */
public class JExtensionPanel extends JPanel {
    private static final long serialVersionUID = 1L;

    public static final int TOOLBAR_ICON_SIZE = 16;

    private boolean expand;// 是否展开
    private String title;// 标题
    private JLabel label;// 标题面板
    private final ActionButtonParam[] actionButtonCfgs;
    private Component contentPanel;// 主面板
    private static final ImageIcon up_icon;
    private static final ImageIcon down_icon;// 图标
    private static final Color titleBgColor = Color.decode("#606060");

    // region 图标初始化
    static {
        String rightIconBase64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAa5JREFUWEfFlzFLw0AUx9+DDlkEdRE/g+BXURAHZ8ExSEzumiL05g42BUGEgoggVETBxcHFwU8gKIIiRRAEEbeCwvXJSVpqbOqlXnK3JXl5/1/ucv97DyFlRFE00+12JzzPe0iLMXEfk0lqtdoyAGwCwLx6hojniNjyfX/fhGAyxw+AWPxomBAi7kkpRblcfjIJkgQ4BYDFNAEiegQAwTk/MAWRBHgHgEmN5M1SqSQ8z3vWiB0ZkgSgDAnvEVEEQXCY4Z1fof8B6CXbVcvCGHsZB8QEgNK9iyFaWSFMAfR0dxzHqbqu+6oLYhpA6d4QkdopxzoQeQB86xLRtvKNSqXyNgokN4BY9DreKcpfho68AXqiDcdxuOu6H39ZcRYf0FniwZhLKeVqGIbKTfujqBnozwRjbN0mwBljbMEaACKeBEGwZA2AiLY45xu2AC6klGthGLZtADQ6nQ4TQnwWvQ3tGZFNK7Z6GFk7jq0WJNZKslyKUlU8TGscc7mV5arEXkkDKKIxUX2hvdZMfXncH1YBYE5dI+IVIjYLaU4Hp75er89KKad837/V+CfGDvkC/FXoIUSHQdsAAAAASUVORK5CYII=";
        up_icon = shrinkIcon(rightIconBase64, TOOLBAR_ICON_SIZE);
        String downIconBase64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAglJREFUWEftlr9rU1EUx899JCAJnUQ6OIg4dGhxFOos0lWQguDQQbCS0qHkfm9w0CgkTc4ZHMQfi0MRBCn9A0p3246lUDoVKaUUByddiuTIKy8hsWnfzySLd7u8c7/fD/d8373X0IiHGbE//Qfo7AAzrxPR/SG1ZAPAmVcHoF6vX8vlcj+GAaCq151zxz0A/oSZl4moMmCINwCW2h7nQsjMp0SUHxDEHwA92ucAGo3GrOd5XwcBYIx5Yq391K3d9zdk5m0iupMxxB6AyX81+wKIyJSq7mYJoKrTzrmtSABBID8Q0XxGEGsAHvbTuvAkrFarhUKh8DsLgGKxOFYqlX7FAvCLReSpqn5MCfEawMuLNELvAmbeJ6KJhBCHAG5ctjYUQETuqepGQoBZAKupAIJAfiGiRzEhOud9agARuamqB3EAPM+bLJfLe2FrQlvQFmDmF0T0Kkww+P4OwEKU2sgAvliz2TwxxoyHCP8EcDWKuV8TC0BEHqvq5xDxRQBvBwIQBPKyh8smgLtRzWPvQHA4Tavqt34mrVZrplKp+ICRR6wWdAXyPRE963YxxqxYa+ciOweFiQBqtdp4Pp//TkRXAp1TVb3lnDsaCkCQhbJ/XZz10Zjn1lr/ORd7JNqBrlbs+P4Absd2TtOCtpmIPFBVD8DaSACSmvaENwuRNBqpMpDGuL125AB/AZhhmCFbx07rAAAAAElFTkSuQmCC";
        down_icon = shrinkIcon(downIconBase64, TOOLBAR_ICON_SIZE);
//        String plusIconBase64 = "iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAMFJREFUWEdjZBhgwDjA9jOQ7QDDtb1+/xj+1zEyMNxj/M+w/nxIyXJyPEO2AwxW90xlYGTIAlnKyMCw7nxISTB9HbCmZz8DA4MD1NIDF0JKHEcdMBoCoyEwGgJDOwQM1/REMjAwhPxnYBAiwSfwkpBoPf8ZrjEyMe48H1y8CVqMQ7QarO1ZxfCfIZRogyhQ+J+R4ezF4BKTweWAAY8CUkPUYLQ2HA2B0RAYDYHREBjojsmAd81IrTtwqSe7b0gtBwAAPxegIWfg4psAAAAASUVORK5CYII=";
//        shrinkIcon(plusIconBase64, TOOLBAR_ICON_SIZE);
    }

    private static ImageIcon shrinkIcon(String iconBase64, int iconHeight) {
        return SwingUtils.shrinkIconFromBase64(iconBase64, iconHeight);
    }
    // endregion

    // ----各种构造函数---------------------------------------

    /**
     * 可以伸缩的面板,默认展开
     */
    public JExtensionPanel() {
        this("", null, true);
    }

    /**
     * 可以伸缩的面板,默认展开
     *
     * @param c 内容面板
     */
    public JExtensionPanel(Component c) {
        this("", null, c, true);
    }

    /**
     * 可以伸缩的面板,默认展开
     *
     * @param title 标题
     * @param c     内容面板
     */
    public JExtensionPanel(String title, Component c) {
        this(title, null, c, true);
    }

    /**
     * 可以伸缩的面板,默认展开
     *
     * @param title 标题
     * @param c     内容面板
     */
    public JExtensionPanel(String title, Component c, boolean expand) {
        this(title, null, c, expand);
    }

    /**
     * 可以伸缩的面板,默认展开
     *
     * @param title 标题
     * @param c     内容面板
     */
    public JExtensionPanel(String title, ActionButtonParam[] actionButtons, Component c) {
        this(title, actionButtons, c, true);
    }

    /**
     * 可以伸缩的面板
     *
     * @param title  标题
     * @param c      内容面板
     * @param expand 默认展开与否
     */
    public JExtensionPanel(String title, ActionButtonParam[] actionButtons, Component c, boolean expand) {
        this.title = title;
        this.actionButtonCfgs = actionButtons == null ? new ActionButtonParam[0] : actionButtons;
        this.expand = expand;
        this.contentPanel = c;
        init();
    }

    // ----各种方法---------------------------------------

    /**
     * 返回面板伸缩的状态	 *
     */
    public boolean isExpand() {
        return expand;
    }

    /**
     * 设置面板的伸缩
     *
     * @param expand  true/false 展开/收缩
     */
    public void setExpand(boolean expand) {
        this.expand = expand;
        if (this.expand) {
            this.label.setIcon(down_icon);
            this.label.setBorder(BorderFactory.createLoweredBevelBorder());
            if (null != this.contentPanel) {
                contentPanel.setVisible(true);
            }
        } else {
            this.label.setIcon(up_icon);
            this.label.setBorder(BorderFactory.createRaisedBevelBorder());
            if (null != this.contentPanel) {
                contentPanel.setVisible(false);
            }
        }
        this.updateUI();
//        this.updateUI();
    }

    /**
     * 返回面板的内容面板
     */
    public Component getContentPanel() {
        return contentPanel;
    }

    /**
     * 设置内容面板
     *
     * @param contentPanel 内容面板
     */
    public void setContentPanel(Component contentPanel) {
        if (null != contentPanel) {
            this.remove(this.contentPanel);
            this.contentPanel = contentPanel;
            this.add(this.contentPanel, BorderLayout.CENTER);
            contentPanel.setVisible(this.expand);
        } else {
            this.remove(this.contentPanel);
            this.contentPanel = null;
        }
        this.updateUI();
    }

    /**
     * 返回面板标题
     */
    public String getTitle() {
        return title;
    }

    /**
     * 设置面板标题
     *
     * @param title 面板标题
     */
    public void setTitle(String title) {
        this.title = title;
        this.label.setText(title);
        this.updateUI();
    }

    /**
     * 创建标题指示图标
     */
    /*private void createImages() {
        int w = this.getPreferredSize().width, h = this.getPreferredSize().height;
        BufferedImage open = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB), close = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);        // 展开的图标
        Graphics2D g2 = open.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(this.getBackground());
        g2.fillRect(0, 0, w, h);
        int[] x = {0, w / 2, w};
        int[] y = {h / 4, 3 * h / 4, h / 4};
        Polygon p = new Polygon(x, y, 3);
        Color openColor = Color.GRAY;
        g2.setPaint(openColor);
        g2.fill(p);
        g2.setPaint(openColor);
        g2.draw(p);
        g2.dispose();
        down_icon = new ImageIcon(open);        // 收缩的的图标
        g2 = close.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setPaint(this.getBackground());
        g2.fillRect(0, 0, w, h);
        x = new int[]{w / 4, 3 * w / 4, w / 4};
        y = new int[]{0, h / 2, h};
        p = new Polygon(x, y, 3);
        g2.setPaint(Color.GRAY);
        g2.fill(p);
        g2.setPaint(Color.GRAY);
        g2.draw(p);
        g2.dispose();
        up_icon = new ImageIcon(close);
    }
     */

    /**
     * 初始化工作
     */
    private void init() {
//        this.createImages();// 获得图标
        this.setLayout(new BorderLayout());
        this.setBackground(titleBgColor);
        if (this.expand) {
            this.label = new JLabel(this.title, down_icon, SwingConstants.LEADING);
//            this.label.setBorder(BorderFactory.createLoweredBevelBorder());
            if (null != this.contentPanel) {
                this.add(this.contentPanel, BorderLayout.CENTER);
            }
        } else {
            this.label = new JLabel(this.title, up_icon, SwingConstants.LEADING);
//            this.label.setBorder(BorderFactory.createRaisedBevelBorder());
            if (null != this.contentPanel) {
                this.add(this.contentPanel, BorderLayout.CENTER);
                this.contentPanel.setVisible(false);
            }
        }
        this.label.setIconTextGap(4);
        Font currentFont = this.label.getFont();
        this.label.setFont(new Font(currentFont.getName(), Font.BOLD, 14));

        JPanel panel = new JPanel(new BorderLayout());
        panel.setBorder(BorderFactory.createLineBorder(Color.GRAY, 1));
        panel.add(this.label, BorderLayout.WEST);

        // 创建按钮
        createButtons(panel, BorderLayout.EAST);

        this.add(panel, BorderLayout.NORTH);

//        this.add(this.label, BorderLayout.NORTH);
        this.label.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (e.getSource() == label) {
                    expand = !expand;
                    if (expand) {
                        label.setIcon(down_icon);
//                        label.setBorder(BorderFactory.createLoweredBevelBorder());
                        if (null != contentPanel) {
                            contentPanel.setVisible(true);
                        }
                    } else {
                        label.setIcon(up_icon);
//                        label.setBorder(BorderFactory.createRaisedBevelBorder());
                        if (null != contentPanel) {
                            contentPanel.setVisible(false);
                        }
                    }
                    updateUI();
                }
            }
        });
    }

    private void createButtons(JPanel panel, String position) {
        if (this.actionButtonCfgs.length == 0)
            return;

        JPanel actionPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));

        for (ActionButtonParam param : this.actionButtonCfgs) {
            ImageIcon icon = param.icon;
            if (param.icon.getIconHeight() != TOOLBAR_ICON_SIZE) {
                Image img = icon.getImage().getScaledInstance(TOOLBAR_ICON_SIZE, TOOLBAR_ICON_SIZE, Image.SCALE_SMOOTH);
                icon = new ImageIcon(img);
            }
            JButton btn = new JButton(param.text, icon);
            btn.setPreferredSize(new Dimension(TOOLBAR_ICON_SIZE, TOOLBAR_ICON_SIZE));
            btn.setBorderPainted(false);
            btn.setOpaque(false);
//        btn.setBackground(panel.getBackground());
//        btn.setUI(new MetalButtonUI() {
//            protected void paintButtonPressed(Graphics g, AbstractButton b) {
//                if ( b.isContentAreaFilled() ) {
////		            Dimension size = b.getSize();
//                    g.setColor(getSelectColor());
////		            g.fillRect(0, 0, size.width, size.height);
//                }
//            }
//        });
//        btn.setFocusPainted(true);
//        btn.setContentAreaFilled(true);
//        btn.setBackground(new Color(0,0,0,0));  // 背景透明
//        btn.setBorder(BorderFactory.createEmptyBorder());
            btn.addActionListener(CommonUtil.debounce(btn, param.action));

            actionPanel.add(btn);
        }

        panel.add(actionPanel, BorderLayout.EAST);
    }

    // ----接口方法的实现---------------------------------------

    private static JPanel createPanel() {
        JPanel p = new JPanel(new FlowLayout());
        JButton b = new JButton("test");
        b.setSize(100, 30);
        JButton b2 = new JButton("test");
        b.setSize(100, 30);
        p.add(b);
        p.add(b2);
        p.setSize(200, 100);
        p.setBorder(BorderFactory.createLineBorder(Color.YELLOW, 2));
        return p;
    }

    public static void main(String[] args) {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container c = f.getContentPane();

        JExtensionPanelAdaptor extensionPanelAdaptor = new JExtensionPanelAdaptor(c);
        extensionPanelAdaptor.add("test1", createPanel());
        extensionPanelAdaptor.add("test2", createPanel());
        extensionPanelAdaptor.add("test3", createPanel());
        extensionPanelAdaptor.add("test4", createPanel());
        extensionPanelAdaptor.add("test5", createPanel());

        f.setSize(360, 500);
        f.setLocation(200, 100);
        f.setVisible(true);
    }


    public static final class ActionButtonParam {
        private final String text;
        private final ImageIcon icon;
        private final ActionListener action;

        public ActionButtonParam(String text, ImageIcon icon, ActionListener action) {
            this.text = text;
            this.icon = icon;
            this.action = action;
        }

        public String getText() {
            return text;
        }

        public ImageIcon getIcon() {
            return icon;
        }

        public ActionListener getAction() {
            return action;
        }
    }
}